package com.syl.starter.itools.base.beans;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.syl.starter.itools.base.enums.ResponseCodeEnum;
import com.syl.starter.itools.common.utils.StringUtils;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 通用返回的实体对象
 * ZJL
 * 2019/5/20 8:26
 */
@Getter
@ToString
@Accessors(chain = true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Response {
    private int code;
    private Object data;
    private String message;

    public Response(ResponseCodeEnum code, Object data){
        this(code, data, null);
    }

    /**
     * 按需构造应答
     * @param code
     * @param data
     * @param message
     */
    public Response(ResponseCodeEnum code, Object data, String message) {
        setResponse(code, data, message);
    }

    /**
     * 简单设置成功应答
     * @return
     */
    public Response setSucceed(){
        setResponse(ResponseCodeEnum.OK, null, ResponseCodeEnum.OK.getMessage());
        return this;
    }

    /**
     * 设置成功数据应答
     * @param data
     * @return
     */
    public Response setSucceedData(Object data){
        setResponse(ResponseCodeEnum.OK, data, null);
        return this;
    }

    /**
     * 设置成功消息应答
     * @param message
     * @return
     */
    public Response setSucceedMsg(String message){
        setResponse(ResponseCodeEnum.OK, null, message);
        return this;
    }

    /**
     * 设置失败应答
     * @param code
     * @return
     */
    public Response setFail(ResponseCodeEnum code){
        setResponse(code, null, code.getMessage());
        return this;
    }

    /**
     * 设置失败消息应答
     * @param code
     * @param message
     * @return
     */
    public Response setFail(ResponseCodeEnum code, String message){
        setResponse(code, null, message);
        return this;
    }

    /**
     * 设置应答
     * @param code
     * @param data
     * @param message
     * @return
     */
    private Response setResponse(ResponseCodeEnum code, Object data, String message){
        this.code = code.getCode();
        this.data = data;
        this.message = StringUtils.isEmpty(message) ? code.getMessage() : message;
        return this;
    }

    public Response(int code, Object data) {
        this.code = code;
        this.data = data;
    }

    public Response(int code, Object data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

}
